
Partial Class RIAssessments_AssessmentActivityCosts
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        SetupJavaScript()
        ClearStatus()
        If Not Page.IsPostBack Then
            Me.BindGrid()
        End If

        ' Set up javascript function to populate new values.
        Me.CalculateNewValuesButton.Attributes.Add("onclick", "javascript: return CalculateNewValues(document.getElementById('" & Me.PercentIncreaseTextBox.ClientID & "').value, '" & Me.AssessmentActivityCostGridView.ClientID & "');")

    End Sub

    Private Sub SetupJavaScript()
        EntityController.JavaScriptAddChildDiv(Me.PageDiv.ClientID, 100)
        EntityController.JavaScriptSetFixedHeight(30)
    End Sub
    Private Sub SetStatus(ByVal message As String)
        Dim mymaster As ASP.admin_admin_master = CType(Me.Master, ASP.admin_admin_master)
        mymaster.SetStatus(message)
    End Sub
    Private Sub ClearStatus()
        SetStatus("")
    End Sub


    Protected Sub BindGrid()

        Dim assessmentActivityCosts As System.Collections.Generic.List(Of Cdm.RIDataCore.Assessments.AssessmentActivityTimeDisplay) = Cdm.RIDataCore.Assessments.AssessmentActivityTimeDisplay.ListByLatestEffectiveDate

        ' Determine if an costs exist.
        If assessmentActivityCosts.Count > 0 Then
            Me.AssessmentActivityCostGridView.DataSource = assessmentActivityCosts
            Me.CalculateNewValuesButton.Enabled = True
        Else
            ' Load the gridview with a generic empty dataset.
            Me.CalculateNewValuesButton.Enabled = False
            Me.AssessmentActivityCostGridView.DataSource = Me.BuildEmptyDataSet
        End If
        Me.AssessmentActivityCostGridView.DataBind()

    End Sub

    Protected Sub AssessmentActivityCostGridView_RowDataBound(ByVal sender As Object, _
                                                              ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) _
                                                              Handles AssessmentActivityCostGridView.RowDataBound

        If e.Row.RowType = DataControlRowType.DataRow Then

            ' Format currency and date fields within the grid.
            Dim effectiveDateTextBox As Label = CType(e.Row.Cells(5).Controls(1), Label)
            If e.Row.RowState = DataControlRowState.Normal OrElse e.Row.RowState = DataControlRowState.Alternate Then
                If IsDate(effectiveDateTextBox.Text) Then
                    effectiveDateTextBox.Text = Microsoft.VisualBasic.FormatDateTime(effectiveDateTextBox.Text, DateFormat.ShortDate)
                    Me.LastEffectiveDateHidden.Value = effectiveDateTextBox.Text
                End If
            End If

        ElseIf e.Row.RowType = DataControlRowType.Footer Then

            e.Row.Cells(4).ColumnSpan = 2

        End If

    End Sub

    Protected Sub SaveButton_Click(ByVal sender As Object, _
                                   ByVal e As System.EventArgs) _
                                   Handles SaveButton.Click

        Dim previouseffectiveDate As DateTime
        Dim effectiveDate As String = CType(Me.AssessmentActivityCostGridView.FooterRow.Cells(4).Controls(1), TextBox).Text

        previouseffectiveDate = CDate(Me.LastEffectiveDateHidden.Value)
        If Not IsDate(effectiveDate) Then
            'Me.ShowMessage("An invalid effective date was entered.", Drawing.Color.Firebrick)
            SetStatus("An invalid effective date was entered.")
        ElseIf CDate(effectiveDate) < previouseffectiveDate Then
            SetStatus("Effective date must not be earlier than the previous effective date of " & previouseffectiveDate.ToShortDateString())
        Else
            Dim isSameEffectiveDate As Boolean = False
            If CDate(effectiveDate).Equals(previouseffectiveDate) Then
                isSameEffectiveDate = True
            End If
            Dim assessmentActivityCost As Cdm.RIDataCore.Assessments.AssessmentActivityTime
            Dim UnitTimeTextBox As TextBox
            Dim functionalUnitTimeTextBox As TextBox
            Dim row As GridViewRow
            Dim trans As New Gentle.Framework.Transaction()
            For Each row In Me.AssessmentActivityCostGridView.Rows

                ' Get a reference to the input controls within the grid.
                UnitTimeTextBox = CType(row.Cells(2).FindControl("NewUnitTimeTextBox"), TextBox)
                functionalUnitTimeTextBox = CType(row.Cells(4).FindControl("NewFunctionalUnitTimeTextBox"), TextBox)

                If UnitTimeTextBox IsNot Nothing And functionalUnitTimeTextBox IsNot Nothing Then

                    If Not isValidEntry(UnitTimeTextBox, functionalUnitTimeTextBox) Then
                        trans.Rollback()
                        'Me.ShowMessage("All task times must be entered, and greater than 0.  Found first error on activity: " & CType(row.Cells(0).Controls(1), Label).Text, Drawing.Color.Firebrick)
                        SetStatus("All task times must be entered, and greater than 0.  Found first error on activity: " & CType(row.Cells(0).Controls(1), Label).Text)
                        Exit Sub
                    End If

                    If isSameEffectiveDate Then
                        Dim currentId As Integer = CInt(Me.AssessmentActivityCostGridView.DataKeys(row.RowIndex).Values(0))
                        assessmentActivityCost = Cdm.RIDataCore.Assessments.AssessmentActivityTime.Retrieve(currentId)
                        assessmentActivityCost.EffectiveDate = CDate(effectiveDate)
                        assessmentActivityCost.UnitTime = CDbl(UnitTimeTextBox.Text)
                        assessmentActivityCost.FunctionalUnitTime = CDbl(functionalUnitTimeTextBox.Text)
                        assessmentActivityCost.Persist(trans)
                    Else
                        assessmentActivityCost = New Cdm.RIDataCore.Assessments.AssessmentActivityTime(Me.AssessmentActivityCostGridView.DataKeys(row.RowIndex).Values(1), _
                                                                                                   IIf(IsNumeric(UnitTimeTextBox.Text), UnitTimeTextBox.Text, 0), _
                                                                                                   IIf(IsNumeric(functionalUnitTimeTextBox.Text), functionalUnitTimeTextBox.Text, 0), _
                                                                                                   CDate(effectiveDate), _
                                                                                                   Nothing, _
                                                                                                   UserAuthorization.CurrentUser.LogonId)
                    End If

                    assessmentActivityCost.Persist(trans)

                End If

            Next
            trans.Commit()
            Me.BindGrid()
            SetStatus("Assessment costs saved successfully.")
            'Me.ShowMessage("Assessment costs saved successfully.", Drawing.Color.Navy)

        End If

    End Sub

    Private Function IsValidEntry(ByVal txt1 As TextBox, ByVal txt2 As TextBox) As Boolean
        If Not (IsNumeric(txt1.Text) And IsNumeric(txt2.Text)) Then
            Return False
        Else
            If Not (Convert.ToDecimal(txt1.Text) > 0 And Convert.ToDecimal(txt2.Text) > 0) Then
                Return False
            End If
        End If
        Return True
    End Function

    Private Sub ShowMessage(ByVal message As String, _
                            ByVal color As System.Drawing.Color)

        ' Displays a message in the message label located in the top right corner of this section.
        Me.MessageLabel.ForeColor = color
        Me.MessageLabel.Text = message
        Me.MessageLabel.Visible = True

    End Sub

    Protected Sub CalculateNewValuesButton_Click(ByVal sender As Object, _
                                                 ByVal e As System.EventArgs) _
                                                 Handles CalculateNewValuesButton.Click

        Dim UnitTimeLabel As Label
        Dim functionalUnitTimeLabel As Label
        Dim UnitTimeTextBox As TextBox
        Dim functionalUnitTimeTextBox As TextBox
        Dim row As GridViewRow
        For Each row In Me.AssessmentActivityCostGridView.Rows

            If row.RowType = DataControlRowType.DataRow Then

                ' Get a reference to the input controls and labels needed to do the calculations.
                UnitTimeLabel = CType(row.Cells(1).FindControl("UnitTimeLabel"), Label)
                UnitTimeTextBox = CType(row.Cells(2).FindControl("NewUnitTimeTextBox"), TextBox)
                functionalUnitTimeLabel = CType(row.Cells(3).FindControl("FunctionalUnitTimeLabel"), Label)
                functionalUnitTimeTextBox = CType(row.Cells(4).FindControl("NewFunctionalUnitTimeTextBox"), TextBox)

                ' Do calculations.
                If IsNumeric(UnitTimeLabel.Text) Then
                    UnitTimeTextBox.Text = (CDbl(UnitTimeLabel.Text) + (CDbl(UnitTimeLabel.Text) * (CDbl(Me.PercentIncreaseTextBox.Text) / 100))).ToString
                    UnitTimeTextBox.Text = FormatNumber(UnitTimeTextBox.Text, 2)
                End If
                If IsNumeric(functionalUnitTimeLabel.Text) Then
                    functionalUnitTimeTextBox.Text = (CDbl(functionalUnitTimeLabel.Text) + (CDbl(functionalUnitTimeLabel.Text) * (CDbl(Me.PercentIncreaseTextBox.Text) / 100))).ToString
                    functionalUnitTimeTextBox.Text = FormatNumber(functionalUnitTimeTextBox.Text, 2)
                End If

            End If

        Next

    End Sub

    Protected Function BuildEmptyDataSet() As Data.DataTable

        ' Builds an empty dataset for the first time assessment activity costs are set up.
        ' i.e. no costs have been set up yet.  Provides an empty grid with essential assessment
        ' activity information to enter values in.

        Dim emptyDataSet As New Data.DataSet

        If emptyDataSet.Tables.Count = 0 Then
            emptyDataSet.Tables.Add("EmptyTable")
            With emptyDataSet.Tables("EmptyTable").Columns
                .Add("AssessmentActivityTimeId")
                .Add("AssessmentActivityId")
                .Add("AssessmentActivity")
                .Add("UnitTime")
                .Add("FunctionalUnitTime")
                .Add("EffectiveDate")
            End With
        End If

        Dim assessmentActivity As Cdm.RIDataCore.Assessments.AssessmentActivity
        Dim assessmentActivities As System.Collections.Generic.List(Of Cdm.RIDataCore.Assessments.AssessmentActivity)
        assessmentActivities = Cdm.RIDataCore.Assessments.AssessmentActivity.ListAll

        Dim index As Integer = 1
        Dim row As Data.DataRow
        For Each assessmentActivity In assessmentActivities

            row = emptyDataSet.Tables("EmptyTable").NewRow

            row.Item("AssessmentActivityTimeId") = index
            row.Item("AssessmentActivityId") = assessmentActivity.AssessmentActivityId
            row.Item("AssessmentActivity") = assessmentActivity.Description
            row.Item("UnitTime") = ""
            row.Item("FunctionalUnitTime") = ""
            row.Item("EffectiveDate") = ""

            emptyDataSet.Tables("EmptyTable").Rows.Add(row)

            index += 1

        Next

        Return emptyDataSet.Tables("EmptyTable")

    End Function

End Class
